﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Data;
using System.Windows;
using System.Windows.Controls;

using Safe_Driving.TokenUser;

namespace Safe_Driving
{
    public partial class MainWindow
    {
        /// <summary>
        /// Init the tab
        /// </summary>
        public void initPrefTab()
        {
            resetFields();
            setComportement();
            refreshDataGridExamsPref();
            
        }


        /// <summary>
        /// Add exam pref
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddExamPref_Click(object sender, RoutedEventArgs e)
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;

            string type = "";
            if(radioButtonAuto.IsChecked == true) {
                type = "Auto";
            } else if(radioButtonMoto.IsChecked == true) {
                type = "Moto";
            } else if(radioButtonCode.IsChecked == true) {
                type = "Code";
            }

            SFExamEn ex = new SFExamEn()
            {
                Date = (DateTime) datePickerExamPref.SelectedDate,
                NoM = textBoxNameExamPref.Text,
                NBPlaces = Int32.Parse(textBoxNbPlaceExamPref.Text),
                Type = type
            };
         
            app.SFExamEn.InsertOnSubmit(ex);

            app.SubmitChanges();

            refreshDataGridExamsPref();
            resetFields();
        }

        /// <summary>
        /// Delete exam pref
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDeleteExamPref_Click(object sender, RoutedEventArgs e)
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;

            SFExamEn ex = (SFExamEn)dataGridExamsPref.SelectedItem;
            app.SFExamEn.DeleteOnSubmit(ex);
            app.SubmitChanges();

            // Gérer suppression liste clients inscrits
            var passe = from p in app.SFPasse
                        where p.IDExamEn == ex.IDExamEn
                        select p;

            app.SFPasse.DeleteAllOnSubmit(passe);
            app.SubmitChanges();

            refreshDataGridExamsPref();
        }

        /// <summary>
        /// Generate the list of candidats for the exam basing on marks
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonGenerateListCandidatExamPref_Click(object sender, RoutedEventArgs e)
        {

            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;

            //Récupére toutes les notes des inscrits
            var q = from cl in app.SFInSCrIt
                    where cl.Note != -1
                    orderby cl.IDClient
                    select cl;
            
            //Fait la moyenne
            int somme = 0, it = 0, lastID = 0;
            Dictionary<int, int> lisMoy = new Dictionary<int, int>();

            foreach(SFInSCrIt o in q) {
                //New ID
                if (lastID != o.IDClient)
                {
                    if (lastID != 0)
                    {
                        lisMoy.Add(lastID, (somme / it));
                    }

                    lastID = o.IDClient;
                    somme = (int) o.Note;
                    it = 1;
                }
                //Somme case
                else
                {
                    lastID = o.IDClient;
                    somme += (int) o.Note;
                    it++;
                }
            }

            lisMoy.Add(lastID, (somme / it));
            
            var req = (from x in lisMoy
                      orderby x.Value
                      select x).Take(((SFExamEn)dataGridExamsPref.SelectedItem).NBPlaces + 5);

                foreach (var o in req)
            {
                app.SFPasse.InsertOnSubmit(
                    new SFPasse()
                    {
                        IDClient = o.Key,
                        IDExamEn = ((SFExamEn)dataGridExamsPref.SelectedItem).IDExamEn
                    });
            }

            app.SubmitChanges();
            refreshDataGridListCandidatExam();
        }

     

        //Window Methods  

        /// <summary>
        /// reset les fields de la fenêtre
        /// </summary>
        private void resetFields()
        {
            textBoxNameExamPref.Text = String.Empty;
            textBoxNbPlaceExamPref.Text = String.Empty;
        }

        /// <summary>
        /// Refresh DataGridListCandidatExam sur candidats
        /// </summary>
        /// <returns>True si il y a rien de rafraichi dans la datagrid</returns>
        private bool refreshDataGridListCandidatExam()
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;

            try
            {
                int i = ((SFExamEn)dataGridExamsPref.SelectedItem).IDExamEn;
                var q = from exs in app.SFPasse
                        join cl in app.SFClient on exs.IDClient equals cl.IDClient
                        where exs.IDExamEn == i
                        select new SFClient
                        {
                            NoM = cl.NoM,
                            PreNoM = cl.PreNoM,
                            IDClient = cl.IDClient
                        };

                dataGridListCandidatExam.ItemsSource = q;

                if (((IEnumerable<SFClient>)q).Count() != 0)
                {
                    return false;
                }
                return true;
            }
            catch (System.Exception e)
            {
                dataGridListCandidatExam.ItemsSource = null;
                return false;
            }
        }

        /// <summary>
        /// refresh la dataGridExamPref
        /// </summary>
        private void refreshDataGridExamsPref()
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;

            var q = (from exs in app.SFExamEn
                     select exs);

            dataGridExamsPref.ItemsSource = q;
        }
     

        //EVT comportement windows
        private void textBoxNameExamPref_TextChanged(object sender, TextChangedEventArgs e)
        {
            setComportement();
        }

        private void textBoxNbPlaceExamPref_TextChanged(object sender, TextChangedEventArgs e)
        {
            setComportement();
        }

        private void dataGridExamsPref_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            setComportement();
            buttonGenerateListCandidatExamPref.IsEnabled = refreshDataGridListCandidatExam();
        }

        private void setComportement()
        {
            if (textBoxNbPlaceExamPref.Text == String.Empty ||
                textBoxNameExamPref.Text == String.Empty)
            {
                buttonAddExamPref.IsEnabled = false;
            }
            else
            {
                buttonAddExamPref.IsEnabled = true;
            }

            if (dataGridExamsPref.SelectedIndex != -1)
            {
                buttonGenerateListCandidatExamPref.IsEnabled = true;
                buttonDeleteExamPref.IsEnabled = true;
            }
            else
            {
                buttonGenerateListCandidatExamPref.IsEnabled = false;
                buttonDeleteExamPref.IsEnabled = false;
            }

        }

    }
}
